package com.hissy.cn.config;

import com.mongodb.MongoClientURI;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

/**
 * @author zhangyanfei
 * @date 2019/11/28
 **/
@Configuration
// 自动实现接口定义
@EnableMongoRepositories(basePackages = "com.hissy.cn.mongodb", mongoTemplateRef = "mongoTemplate")
public class MongodbConfig {

    private ApplicationContext applicationContext;

    public MongodbConfig(ApplicationContext applicationContext){
        this.applicationContext = applicationContext;
    }

    @Primary
    @Bean("mongoTemplate")
    public MongoTemplate caoCaoMongoTemplate() {
        MongoDbFactory factory = caoCaoMongoFactory(caoCaoMongoProperties());

        //begin: Don't save _class to mongo
        MongoMappingContext mongoMappingContext = new MongoMappingContext();
        mongoMappingContext.setApplicationContext(applicationContext);
        MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(factory), mongoMappingContext);
        converter.setTypeMapper(new DefaultMongoTypeMapper(null));
        //end: Don't save _class to mongo

        return new MongoTemplate(factory,converter);
    }

    @Primary
    @Bean("mongoFactory")
    public MongoDbFactory caoCaoMongoFactory(MongoProperties mongoProperties) {
        MongoClientURI clientUri = new MongoClientURI(mongoProperties.getUri());
        return new SimpleMongoDbFactory(clientUri);
    }

    @Bean("mongoProperties")
    @Primary
    @ConfigurationProperties(prefix = "spring.data.mongodb")
    public MongoProperties caoCaoMongoProperties() {
        System.out.println("-------------------- mongoProperties init ---------------------");
        return new MongoProperties();
    }
}
